const McMeeting = require('./db/mc_meeting')
const McMeetingUserRelation = require('./db/mc_meeting_user_relation')
const User = require('./db/user')
const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

let myHandler = async function (event, context, callback, logger) {
  const { meetingId } = event.body ? JSON.parse(event.body) : event

  logger.info("meetingId:", meetingId);

  
  if(!meetingId) {
    callback({
      code: 400,
      msg: "meetingId 不能为空",
      data: null
    })
  } else {
    // 查询会议信息
    let cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeeting.mc_meeting)
    let userCloudDBZoneQuery = cloudDBZoneQuery.equalTo('id', meetingId)
    const respMeeting = mCloudDBZone.executeQuery(userCloudDBZoneQuery);

    // 查询参与人信息
    let relationQuery = clouddb.CloudDBZoneQuery.where(McMeetingUserRelation.mc_meeting_user_relation).equalTo('meetingId', meetingId)
    const respUser = mCloudDBZone.executeQuery(relationQuery).then((response) => {
      const relations = response.getSnapshotObjects()
      logger.info('relations', relations)
      if(relations?.length !== 0) {
        const userQuery = clouddb.CloudDBZoneQuery.where(User.user).in('id', relations.map(r => r.userId))
        return mCloudDBZone.executeQuery(userQuery)
      }
      return response
    })

    const [meetingResp, userResp] = await Promise.all([respMeeting, respUser])

    const meetingData = meetingResp.getSnapshotObjects()[0]
    const userData = userResp.getSnapshotObjects() || []

    // 获取当前用户信息
    const userQuery = clouddb.CloudDBZoneQuery.where(User.user).equalTo("id", meetingData.createBy)
    const respUserInfo = await mCloudDBZone.executeQuery(userQuery)
    const userInfo = respUserInfo.getSnapshotObjects()

    logger.info('meeting data', meetingData)
    logger.info('user data', userData)

    meetingData.relationUsers = [...userInfo, ...userData]
    callback({
      code: 200,
      msg: "成功",
      meetingData
    })
  }
};

export { myHandler };